#include "AuraEffectActor.h"

#include "AbilitySystemInterface.h"
#include "AbilitySystemBlueprintLibrary.h"
#include "AbilitySystem/AuraAttributeSet.h"
#include "Components/SphereComponent.h"

AAuraEffectActor::AAuraEffectActor()
{
	PrimaryActorTick.bCanEverTick = false;
	RootComponent = CreateDefaultSubobject<USceneComponent>("RootComp");
}


void AAuraEffectActor::BeginPlay()
{
	Super::BeginPlay();
	
}

void AAuraEffectActor::ApplyEffectToTarget(AActor* TargetActor, TSubclassOf<UGameplayEffect> GameplayEffectClass)
{
	if(UAbilitySystemComponent* TargetASC = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(TargetActor))
	{
		check(GameplayEffectClass);
		FGameplayEffectContextHandle EffectContextHandle = TargetASC->MakeEffectContext();
		//设置产生此效果的对象
		EffectContextHandle.AddSourceObject(this);
		//ActorLevel是此效果的一个等级，比如基础加血5滴  ActorLevel=3的话 就是 3*5=15 这样
		const FGameplayEffectSpecHandle EffectSpecHandle = TargetASC->MakeOutgoingSpec(GameplayEffectClass,ActorLevel,EffectContextHandle);
		const FActiveGameplayEffectHandle _ActiveEffectHandle =  TargetASC->ApplyGameplayEffectSpecToSelf(*EffectSpecHandle.Data.Get());
		const bool bIsInfinite = EffectSpecHandle.Data->Def->DurationPolicy == EGameplayEffectDurationType::Infinite;
		if(bIsInfinite&&InfiniteRemovenPolicy==EEffectRemovenPolicy::RemoveOnEndOverlap)
		{
			ActiveEffectHandleMap.Add(_ActiveEffectHandle,TargetASC);
		}
	}
}

void AAuraEffectActor::OnBeginOverlap(AActor* TargetActor)
{
	if(InstantApplicationPolicy==EEffectApplicationPolicy::ApplyOnOverlap)
	{
		ApplyEffectToTarget(TargetActor,InstantGameplayEffectClass);
	}
	if(DuationApplicationPolicy==EEffectApplicationPolicy::ApplyOnOverlap)
	{
		ApplyEffectToTarget(TargetActor,DuationGameplayEffectClass);
	}
	if(InfiniteApplicationPolicy==EEffectApplicationPolicy::ApplyOnOverlap)
	{
		ApplyEffectToTarget(TargetActor,InfiniteGameplayEffectClass);
	}
	if(bDestroyOnEffectRemoval)
	{
		Destroy();
	}
}

void AAuraEffectActor::OnEndOverlap(AActor* TargetActor)
{
	if(InstantApplicationPolicy==EEffectApplicationPolicy::ApplyOnEndOverlap)
	{
		ApplyEffectToTarget(TargetActor,InstantGameplayEffectClass);
	}
	if(DuationApplicationPolicy==EEffectApplicationPolicy::ApplyOnEndOverlap)
	{
		ApplyEffectToTarget(TargetActor,DuationGameplayEffectClass);
	}
	if(InfiniteApplicationPolicy==EEffectApplicationPolicy::ApplyOnEndOverlap)
	{
		ApplyEffectToTarget(TargetActor,InfiniteGameplayEffectClass);
	}
	if(InfiniteRemovenPolicy==EEffectRemovenPolicy::RemoveOnEndOverlap)
	{
		if(UAbilitySystemComponent* TargetASC = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(TargetActor))
		{
			TArray<FActiveGameplayEffectHandle> HandlesToRemove;
			for(auto It :ActiveEffectHandleMap)
			{
				if(TargetASC == It.Value)
				{
					TargetASC->RemoveActiveGameplayEffect(It.Key,1);
					HandlesToRemove.Add(It.Key);
				}
			}
			for(auto& Handle:HandlesToRemove)
			{
				ActiveEffectHandleMap.FindAndRemoveChecked(Handle);
			}
		}
	}
	
}
